<template>
  <div class="app-container">
    <!-- 标题栏 -->
    <div class="header-bar">
      <el-button type="primary" class="mb-4" @click="handleAdd">新建合同</el-button>
      <el-input
        placeholder="请输入合同编号/名称"
        style="width: 240px; float: right; margin-bottom: 20px"
        v-model="query.keyword"
        @keyup.enter="handleSearch"
        clearable
      >
        <template #append>
          <el-button icon="Search" @click="handleSearch"></el-button>
        </template>
      </el-input>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="contractList"
      style="width: 100%"
      border
      row-key="cno"
      v-loading="loading"
      ref="tableRef"
      :expand-row-keys="expandRowKeys"
      :row-class-name="getRowClassName"
      @expand-change="handleExpandChange"
    >
      <!-- 展开列 - 保持简单，让Element Plus自动控制显示 -->
      <el-table-column type="expand" fixed="left">
        <template #default="{ row }">
          <!-- 展开内容：合同分支表格 -->
          <div v-if="loadingRows.has(row.cno)" class="loading-container">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span style="margin-left: 8px">加载中...</span>
          </div>
          <div v-else-if="row.children && row.children.length > 0">
            <el-table
              :data="row.children"
              border
              :row-key="(subRow) => subRow.uniqueKey || subRow.contractNo"
              class="sub-table"
            >
              <el-table-column
                prop="contractNo"
                label="合同分支"
                align="left"
                width="150"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                prop="dno"
                label="需求编号"
                width="150"
                align="left"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                prop="dname"
                label="需求名称"
                width="200"
                align="left"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                prop="status"
                label="当前状态"
                width="100"
                align="left"
                :show-overflow-tooltip="true"
              >
                <template #default="scope">
                  <span>{{ getRequirementStatusLabel(scope.row.status) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="金额(万元)" align="left" width="150" />
              <el-table-column
                prop="materialName"
                label="物料类型"
                width="150"
                align="left"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                prop="createBy"
                label="创建人"
                width="150"
                align="left"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                prop="createTime"
                label="创建时间"
                width="200"
                align="left"
                :show-overflow-tooltip="true"
              />
              <el-table-column label="操作" align="center" width="80" fixed="right">
                <template #default="{ row: subRow }">
                  <el-dropdown>
                    <span class="el-dropdown-link">
                      操作
                      <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="handleViewSub(subRow)">查看</el-dropdown-item>
                        <el-dropdown-item @click="handleDownloadContract(subRow)"
                          >下载</el-dropdown-item
                        >
                        <template v-if="subRow.status === '1' || subRow.status === 1">
                          <el-dropdown-item @click="handleSubmitSub(subRow)">提交</el-dropdown-item>
                        </template>
                        <template v-if="subRow.status === '2' || subRow.status === 2">
                          <el-dropdown-item @click="handleReviewProcess(subRow)"
                            >审批流程</el-dropdown-item
                          >
                        </template>
                        <template v-if="subRow.delFlag !== '2' && subRow.delFlag !== 2">
                          <el-dropdown-item
                            divided
                            @click="handleDeleteSub(subRow)"
                            style="color: #f56c6c"
                            >删除</el-dropdown-item
                          >
                        </template>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else class="no-children">暂无合同分支</div>
        </template>
      </el-table-column>
      <!-- 主表格列 -->
      <el-table-column
        prop="cno"
        label="合同编号"
        align="left"
        width="180"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="cname"
        label="合同名称"
        align="left"
        :show-overflow-tooltip="true"
      />
      <el-table-column prop="ctype" label="合同类型" align="left" width="120">
        <template #default="scope">
          <span>{{ getCtypeLabel(scope.row.ctype) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="customer"
        label="客户名称"
        align="left"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="deNo"
        label="关联需求编号"
        align="left"
        width="180"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="materialName"
        label="物料类型"
        align="left"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="coStatus"
        label="当前状态"
        align="left"
        width="120"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ scope.row.coStatus === 1 ? '保存' : '确定' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="money" label="合同总金额(万元)" align="left" width="160" />
      <el-table-column
        prop="personInCharge"
        label="负责人"
        align="left"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="left"
        width="180"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="操作" align="center" fixed="right">
        <template #default="scope">
          <el-dropdown>
            <span class="el-dropdown-link" style="line-height: 23px">
              操作 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleView(scope.row)">查看</el-dropdown-item>
                <template v-if="scope.row.ctype === 1">
                  <el-dropdown-item @click="handleEdit(scope.row)">编辑</el-dropdown-item>
                </template>
                <el-dropdown-item @click="handleDownloadContract(scope.row)">下载</el-dropdown-item>
                <template v-if="scope.row.ctype === 1">
                  <el-dropdown-item @click="handleNewBranch(scope.row)">新建分支</el-dropdown-item>
                </template>
                <template v-if="scope.row.status !== 6">
                  <el-dropdown-item divided @click="handleDelete(scope.row)" style="color: #f56c6c"
                    >删除</el-dropdown-item
                  >
                </template>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      style="margin-top: 20px; justify-content: flex-end"
      v-model:current-page="query.pageNum"
      v-model:page-size="query.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 新建/编辑合同弹窗组件 -->
    <CreateModal
      v-model:visible="dialogVisible"
      :is-edit="isEditMode"
      :contract-data="currentContract"
      :ctype-options="ctypeOptions"
      :requirement-options="requirementOptions"
      @submit="handleModalSubmit"
    />

    <!-- 新建分支弹窗 -->
    <el-dialog
      :model-value="branchDialogVisible"
      title="新建分支"
      width="600px"
      @close="handleBranchDialogClose"
    >
      <el-form ref="branchFormRef" :model="branchForm" :rules="branchRules" class="dialog-form">
        <el-descriptions :column="1" border class="custom-descriptions">
          <el-descriptions-item label="合同名称">
            <el-form-item style="margin-top: 16px">
              <el-input v-model="branchForm.cname" disabled style="width: 100%" />
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item label="合同类型">
            <el-form-item style="margin-top: 16px">
              <el-input v-model="branchForm.ctype" disabled style="width: 100%" />
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item label="工程名称">
            <el-form-item style="margin-top: 16px">
              <el-input v-model="branchForm.projectName" disabled style="width: 100%" />
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item label="*关联需求">
            <el-form-item prop="requirementId" style="margin-top: 16px">
              <el-select
                v-model="branchForm.requirementId"
                placeholder="请选择"
                filterable
                style="width: 100%"
                @change="handleBranchRequirementChange"
              >
                <el-option
                  v-for="item in requirementOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item label="需求编号">
            <el-form-item style="margin-top: 16px">
              <el-input
                v-model="branchForm.deNo"
                placeholder="自动回显"
                disabled
                style="width: 100%"
              />
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleBranchDialogClose">取消</el-button>
          <el-button type="primary" @click="handleBranchDialogSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 提交分支 -->
    <el-dialog
      v-model="submitConfirmVisible"
      title=""
      width="400px"
      @close="handleCloseSubmitConfirm"
      :show-close="false"
      class="submit-confirm-dialog"
    >
      <div style="padding: 10px 0">
        <div style="display: flex; align-items: center; margin-bottom: 16px">
          <el-icon style="margin-right: 8px; font-size: 24px; color: #f56c6c">
            <WarningFilled />
          </el-icon>
          <span style="font-size: 16px; font-weight: bold">确认提交合同并下推生产?</span>
        </div>
        <p style="color: #606266">确认后合同无法修改</p>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseSubmitConfirm">取消</el-button>
          <el-button
            @click="handleNotPushSubmit"
            style="
              background-color: #f5f7fa;
              border-color: #dcdfe6;
              color: #606266;
              margin: 0 0 0 12px;
            "
          >
            暂不下推
          </el-button>
          <el-button type="primary" @click="handleConfirmSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 审批流程弹窗组件 -->
    <ApprovalProcedures v-model="reviewProcessVisible" :process-data="reviewProcessData" />

    <!-- 下载合同弹窗组件 -->
    <DownContractStepForm
      v-model="downloadVisible"
      :contract-data="currentDownloadRow || {}"
      @download="handleContractDownloadComplete"
    />

    <!-- 创建合同配置界面 -->
    <!-- <el-dialog
        v-model="createContractInfoVisible"
        title="新建合同配置"
        width="90vw"
        height="90vh"
        :fullscreen="false"
        class="create-contract-dialog"
        @close="handleCreateContractInfoClose"
      >

      </el-dialog> -->
    <!-- <CreateContractInfo
        :contract-info="currentContractInfo"
        @complete="handleContractCreateComplete"
        @save="handleContractSave"
      /> -->
  </div>
</template>

<script setup name="ContractManagement">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { WarningFilled, Edit, ArrowDown, Loading } from '@element-plus/icons-vue'
import ApprovalProcedures from './approvalProcedures.vue'
import DownContractStepForm from './downContractStepForm.vue'
import CreateContractInfo from './createContractInfo.vue'
import CreateModal from './createModal.vue'
// import CreateContractInfo from './createContractInfo.vue'
import { useRouter } from 'vue-router'
import {
  getContractPage,
  getUnassociatedRequirementPage,
  getContractRequirementPage,
  deleteContract,
  deleteContractBranch
} from '@/api/business/contract'

const router = useRouter()

// 查询参数
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
})

// 数据和状态
const contractList = ref([])
const total = ref(0)
const loading = ref(false)
const expandedRows = ref([]) // 用于记录展开的行
const expandRowKeys = ref([]) // 用于控制默认展开的行
const tableRef = ref(null) // 表格引用
const dialogVisible = ref(false) // 弹窗可见性
const loadingRows = ref(new Set()) // 正在加载需求的行
// 提交确认弹窗相关状态
const submitConfirmVisible = ref(false)
const currentSubmitRow = ref(null)
// 审批流程弹窗相关状态
const reviewProcessVisible = ref(false)
const reviewProcessData = reactive({
  approvalNo: '',
  cno: '',
  ctype: '',
  dname: '',
  deNo: '',
  approvalFlow: []
})

// 下载合同弹窗相关状态
const downloadVisible = ref(false)
const currentDownloadRow = ref(null)

// 创建合同配置界面相关状态
// 创建合同配置界面相关状态
const createContractInfoVisible = ref(false)
const currentContractInfo = ref({})

// 编辑模式标志和当前编辑的合同
const isEditMode = ref(false)
const currentContract = ref(null)

// 新建分支相关状态
const branchDialogVisible = ref(false)
const branchForm = reactive({
  cname: '',
  ctype: '',
  projectName: '',
  requirementId: '',
  deNo: ''
})
const branchFormRef = ref(null)
const currentParentContract = ref(null)

// 需求下拉选项 - 模拟数据
const requirementOptions = ref([])

// 分支表单验证规则
const branchRules = {
  requirementId: [{ required: true, message: '请选择关联需求', trigger: 'change' }]
}

// 合同类型选项
const ctypeOptions = ref([
  { label: '工程类', value: 1 },
  { label: '直销类', value: 2 }
])

// 状态选项映射 - 数字到中文
const statusOptions = ref([
  { label: '待提交', value: 1 },
  { label: '审批中', value: 2 },
  { label: '待计划', value: 3 },
  { label: '排产中', value: 4 },
  { label: '出库中', value: 5 },
  { label: '已完成', value: 6 }
])

// 获取状态标签
function getStatusLabel(value) {
  if (value === null || value === undefined || value === '') return ''
  const option = statusOptions.value.find((item) => item.value === value)
  return option ? option.label : ''
}

// 获取需求状态标签（1保存、2确定）
function getRequirementStatusLabel(value) {
  if (value === null || value === undefined || value === '') return ''
  // 处理字符串和数字类型
  const status = String(value)
  if (status === '1') return '保存'
  if (status === '2') return '确定'
  return ''
}

// 获取合同列表
const getContractList = async () => {
  loading.value = true
  getContractPage(query)
    .then((res) => {
      if (res.code === 200) {
        loading.value = false
        const list = res.data?.list || []
        total.value = res.data?.total || 0
        // 保存当前展开的行
        const currentExpandedKeys = [...expandRowKeys.value]
        // 更新列表数据，保留已加载的 children 数据
        contractList.value = list.map((item) => {
          // 查找旧数据中是否有已加载的 children
          const oldItem = contractList.value.find((old) => old.cno === item.cno)
          return {
            ...item,
            // 如果旧数据有 children 且当前展开，保留它；否则初始化为空数组
            children:
              oldItem &&
              oldItem.children &&
              oldItem.children.length > 0 &&
              currentExpandedKeys.includes(item.cno)
                ? oldItem.children
                : []
          }
        })
        // 恢复展开状态
        expandRowKeys.value = currentExpandedKeys.filter((key) =>
          contractList.value.some((item) => item.cno === key)
        )
      }
    })
    .catch(() => {
      loading.value = false
    })
}

// 处理展开行变化
const handleExpandChange = async (row, expandedRows) => {
  // 直销类不能展开
  if (row.ctype === 2) {
    return
  }
  // 如果展开
  if (expandedRows.includes(row)) {
    // 确保展开状态被记录
    if (!expandRowKeys.value.includes(row.cno)) {
      expandRowKeys.value.push(row.cno)
    }

    // 检查是否已经加载过数据
    const contractItem = contractList.value.find((item) => item.cno === row.cno)
    if (contractItem && (!contractItem.children || contractItem.children.length === 0)) {
      await loadContractRequirements(row)
    }
  } else {
    // 如果折叠，从展开列表中移除
    const index = expandRowKeys.value.indexOf(row.cno)
    if (index > -1) {
      expandRowKeys.value.splice(index, 1)
    }
  }
}

// 加载合同下的需求
const loadContractRequirements = async (row) => {
  // 防止重复加载
  if (loadingRows.value.has(row.cno)) {
    return
  }

  loadingRows.value.add(row.cno)

  try {
    const params = {
      deType: row.ctype || '',
      coNo: row.cno || '',
      pageNum: 1,
      pageSize: 1000
    }
    const res = await getContractRequirementPage(params)
    if (res.code === 200) {
      const list = res.data?.list || []
      const children = list.map((item, index) => {
        return {
          uniqueKey: `${row.cno}_${item.id || index}`, // 唯一标识
          ...item,
          _rawData: item // 保留原始数据，方便后续操作
        }
      })
      // 找到 contractList 中对应的行并更新
      const contractIndex = contractList.value.findIndex((item) => item.cno === row.cno)
      if (contractIndex !== -1) {
        contractList.value[contractIndex].children = children
      } else {
        row.children = children
      }

      // 确保表格展开状态（数据加载完成后，确保行保持展开）
      await nextTick()
      // 确保展开状态被记录
      if (!expandRowKeys.value.includes(row.cno)) {
        expandRowKeys.value.push(row.cno)
      }

      // 等待 DOM 更新后再强制刷新表格布局
      await nextTick()
      if (tableRef.value) {
        tableRef.value.doLayout()
      }
    } else {
      // 如果返回失败，设置空数组
      const contractIndex = contractList.value.findIndex((item) => item.cno === row.cno)
      if (contractIndex !== -1) {
        contractList.value[contractIndex].children = []
      } else {
        row.children = []
      }
    }
  } catch (error) {
    console.error('加载合同需求失败:', error)
    ElMessage.error('加载合同需求失败')
    const contractIndex = contractList.value.findIndex((item) => item.cno === row.cno)
    if (contractIndex !== -1) {
      contractList.value[contractIndex].children = []
    } else {
      row.children = []
    }
  } finally {
    loadingRows.value.delete(row.cno)
  }
}
// 获取合同/分支下未关联的需求
const getUnassociatedRequirements = () => {
  getUnassociatedRequirementPage()
    .then((res) => {
      if (res.code === 200) {
        requirementOptions.value = res.data || []
      }
    })
    .catch(() => {
      requirementOptions.value = []
    })
}
// 初始化
onMounted(() => {
  getContractList()
  getUnassociatedRequirements()
})

// 获取合同类型标签
function getCtypeLabel(value) {
  const option = ctypeOptions.value.find((item) => item.value === value)
  return option ? option.label : value
}

// 获取行的类名，用于控制展开图标显示
function getRowClassName({ row }) {
  if (row.ctype === 2) {
    return 'no-expand-row'
  }
  return ''
}

// 搜索
function handleSearch() {
  query.pageNum = 1
  getContractList()
}

// 打开新建合同弹窗
function handleAdd() {
  // 重置表单状态
  resetFormState()
  isEditMode.value = false
  // 显示弹窗
  dialogVisible.value = true
}

// 重置表单状态
function resetFormState() {
  isEditMode.value = false
  currentContract.value = null
}

// 重置分支表单
function resetBranchForm() {
  if (branchFormRef.value) {
    branchFormRef.value.resetFields()
  }
  // 重置默认值
  Object.assign(branchForm, {
    cname: '',
    ctype: '',
    projectName: '',
    requirementId: '',
    deNo: ''
  })
  currentParentContract.value = null
}

// 处理分支需求选择变化
function handleBranchRequirementChange(value) {
  const selected = requirementOptions.value.find((item) => item.value === value)
  if (selected) {
    branchForm.deNo = selected.deNo
  } else {
    branchForm.deNo = ''
  }
}

// 关闭分支弹窗
function handleBranchDialogClose() {
  branchDialogVisible.value = false
  resetBranchForm()
}

// 处理模态框提交
async function handleModalSubmit(formData) {
  try {
    // 打印表单信息
    console.log('最终填写的表单信息:', formData)
    if (isEditMode.value) {
      // 编辑模式
      // TODO: 实现编辑接口调用
    } else {
      // 新建模式
      // 工程类合同已经在弹窗组件内部处理，这里只需要刷新列表
      if (formData.crType === 1) {
        // 刷新合同列表
        getContractList()
      } else if (formData.crType === 2) {
        // 直销类合同，跳转到配置页面
        router.push({ path: '/business/contract/Contract/createContractInfo' })
      }
    }
  } catch (error) {
    console.error('处理表单提交失败:', error)
  }
}

// 查看合同
function handleView(row) {
  if (!row.coId || !row.deId) {
    ElMessage.error('缺少必要参数：合同编号或需求id')
    return
  }

  // 传递合同编号和需求编号
  router.push({
    path: '/business/contract/Contract/contractDetail',
    query: {
      coId: row.id,
      deId: row.deId
    }
  })
}

// 编辑合同
function handleEdit(row) {
  resetFormState()
  isEditMode.value = true
  currentContract.value = row
  dialogVisible.value = true
}

// 下载合同
function handleDownload(row) {
  ElMessage.success(`下载合同：${row.cname}`)
}

// 新建分支
function handleNewBranch(row) {
  resetBranchForm()
  currentParentContract.value = row

  // 回显上级合同信息
  branchForm.cname = row.cname
  branchForm.ctype = row.ctype
  branchForm.projectName = row.projectName || ''

  // 显示弹窗
  branchDialogVisible.value = true
}

// 提交分支表单
async function handleBranchDialogSubmit() {
  try {
    // 验证表单
    await branchFormRef.value.validate()

    // 获取选中的需求信息
    const selectedRequirement = requirementOptions.value.find(
      (item) => item.value === branchForm.requirementId
    )

    // 打印信息
    console.log('新建分支表单信息:', { ...branchForm })

    if (currentParentContract.value) {
      // 查找原始数据中的合同
      const contractIndex = originalData.findIndex(
        (item) => item.cno === currentParentContract.value.cno
      )

      if (contractIndex !== -1) {
        const contract = originalData[contractIndex]

        // 确保children数组存在
        if (!contract.children || !Array.isArray(contract.children)) {
          contract.children = []
        }

        // 生成新的分支编号（当前最大分支号+1）
        const maxBranchNo = contract.children.reduce((max, child) => {
          const branchNo = parseInt(child.branchNo)
          return isNaN(branchNo) ? max : Math.max(max, branchNo)
        }, 0)
        const newBranchNo = (maxBranchNo + 1).toString()

        // 创建新分支数据
        const newBranch = {
          branchNo: newBranchNo,
          deNo: branchForm.deNo,
          dname: selectedRequirement?.dname || '',
          status: 1, // 默认为待提交状态
          amount: '',
          materialName: '',
          creator: '当前用户',
          createTime: new Date().toLocaleString('zh-CN')
        }

        // 添加到children数组
        contract.children.push(newBranch)

        // 重新获取合同列表
        getContractList()

        // 关闭弹窗
        branchDialogVisible.value = false

        // 提示成功
        ElMessage.success('合同分支创建成功')
      }
    }
  } catch (error) {
    console.warn('表单验证失败:', error)
  }
}

// 提交并下推生产
function submitAndPushProduction(row) {
  console.log('确认提交并下推生产:', row)
  // 更新合同状态为审批中
  row.status = 2
  // 重新获取合同列表
  getContractList()
  // 提示成功
  ElMessage.success('合同已提交并下推生产')
}
// 处理提交确认
function handleConfirmSubmit() {
  if (currentSubmitRow.value) {
    submitAndPushProduction(currentSubmitRow.value)
    submitConfirmVisible.value = false
    currentSubmitRow.value = null
  }
}

// 处理暂不下推
function handleNotPushSubmit() {
  if (currentSubmitRow.value) {
    submitOnly(currentSubmitRow.value)
    submitConfirmVisible.value = false
    currentSubmitRow.value = null
  }
}

// 关闭提交确认弹窗
function handleCloseSubmitConfirm() {
  submitConfirmVisible.value = false
  currentSubmitRow.value = null
}

// 仅提交，暂不下推
function submitOnly(row) {
  console.log('仅提交，暂不下推生产:', row)
  // 更新合同状态为待计划
  row.status = 3
  // 重新获取合同列表
  getContractList()
  // 提示成功
  ElMessage.success('合同已提交，暂不下推生产')
}

// 删除合同
function handleDelete(row) {
  ElMessageBox.confirm('确认删除该合同？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deleteContract({
          coId: row.id
        })

        if (res.code === 200) {
          ElMessage.success('删除成功')
          getContractList()
        } else {
          ElMessage.error(res.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除合同失败:', error)
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 查看分支
function handleViewSub(row) {
  // 传递合同编号和需求编号
  router.push({
    path: '/business/contract/Contract/contractDetail',
    query: {
      cno: row.id,
      dno: row.deid
    }
  })
}

// 下载分支
function handleDownloadSub(row) {
  ElMessage.success(`下载分支：${row.dname || row.dName || row.dname}`)
}

// 提交分支
function handleSubmitSub(row) {
  currentSubmitRow.value = row
  submitConfirmVisible.value = true
}

// 查看审批流程
function handleReviewProcess(row) {
  // 模拟审批流程数据
  reviewProcessData.approvalNo = 'SPBH001'
  reviewProcessData.cno = row.contractNo
  reviewProcessData.ctype = row.ctype
  reviewProcessData.dname = row.dname || row.dName || row.dname || '需求名称'
  reviewProcessData.deNo = row.dno || row.dNo || row.deNo || 'XQBH001'

  // 模拟审批流程
  reviewProcessData.approvalFlow = [
    {
      title: 'xx部门审批',
      status: 'approved',
      approver: '张三(zhangsan)',
      comment: '同意',
      time: '2025-04-28 16:09:03'
    },
    {
      title: 'xx部门审批',
      status: 'pending',
      approver: '李四(lisi)',
      comment: '',
      time: ''
    },
    {
      title: 'xx部门审批',
      status: 'pending',
      approver: '',
      comment: '',
      time: ''
    }
  ]

  reviewProcessVisible.value = true
}

// 处理下载合同
function handleDownloadContract(row) {
  ElMessage.warning('下载合同功能开发中，敬请期待！')
  return
  // 准备合同数据，传递 coId 和 deId
  currentDownloadRow.value = {
    ...row,
    coId: row.contractId || row.id,
    deId: row.deid || row.id
  }

  // 显示下载弹窗
  downloadVisible.value = true
}

// 处理合同下载完成
function handleContractDownloadComplete(data) {
  ElMessage.success('合同下载成功')
  console.log('下载合同数据:', data)
  // 这里可以根据需要执行其他操作
}

// 删除分支
function handleDeleteSub(row) {
  ElMessageBox.confirm('确定要删除该分支吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deleteContractBranch({
          coId: row.contractId,
          deId: row.id
        })

        if (res.code === 200) {
          ElMessage.success(`删除分支：${row.dname}`)
          getContractList()
        } else {
          ElMessage.error(res.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除分支失败:', error)
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 分页大小改变
function handleSizeChange(val) {
  query.pageSize = val
  query.pageNum = 1
  getContractList()
}

// 当前页码改变
function handleCurrentChange(val) {
  query.pageNum = val
  getContractList()
}

// 处理创建合同配置界面关闭
function handleCreateContractInfoClose() {
  createContractInfoVisible.value = false
  currentContractInfo.value = {}
}

// 处理合同创建完成
function handleContractCreateComplete(data) {
  // 这里可以添加合同创建完成后的逻辑
  ElMessage.success('合同创建成功')
  createContractInfoVisible.value = false
  currentContractInfo.value = {}
  // 刷新合同列表
  getContractList()
}

// 处理合同保存
function handleContractSave(data) {
  // 这里可以添加合同保存的逻辑
  ElMessage.success('合同保存成功')
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header-bar {
  margin-bottom: 10px;
}

/* 子表格样式 */
.sub-table {
  padding-left: 47px;
}

/* 间距样式 */
.ml5 {
  margin-left: 5px;
}

/* 展开/折叠图标按钮样式 */
.expand-icon-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 无子项提示样式 */
.no-children {
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 弹窗表单样式 */
.custom-descriptions {
  width: 100%;
}

.custom-descriptions .el-descriptions__item {
  display: flex;
  border-bottom: 1px solid #ebeef5;
}

.custom-descriptions .el-descriptions__label {
  width: 120px;
  font-weight: 500;
  color: #606266;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.custom-descriptions .el-descriptions__content {
  flex: 1;
  color: #303133;
  display: flex;
  align-items: center;
  padding: 18px 10px 0 10px !important;
}

.custom-descriptions .el-descriptions__row:last-child .el-descriptions__item {
  border-bottom: none;
}

.el-descriptions__cell--label {
  background-color: transparent !important;
}
:deep(.custom-descriptions .el-descriptions__cell) {
  padding: 0px 11px !important;
}
.el-form-item {
  margin-bottom: 16px;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
}

.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 隐藏直销类合同的展开图标 */
:deep(.no-expand-row .el-table__expand-icon) {
  display: none !important;
}

:deep(.no-expand-row .el-table__placeholder) {
  display: none !important;
}
</style>
